const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

// 获取所有渠道
exports.getAllChannels = async (req, res) => {
  try {
    const channels = await prisma.channel.findMany({
      orderBy: { sortOrder: 'asc' }
    });
    
    res.json({
      status: 'success',
      data: channels
    });
  } catch (error) {
    console.error('获取渠道失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取渠道失败',
      error: error.message
    });
  }
};

// 获取单个渠道
exports.getChannelById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const channel = await prisma.channel.findUnique({
      where: { id: Number(id) }
    });
    
    if (!channel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    res.json({
      status: 'success',
      data: channel
    });
  } catch (error) {
    console.error('获取渠道详情失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取渠道详情失败',
      error: error.message
    });
  }
};

// 创建渠道
exports.createChannel = async (req, res) => {
  try {
    const { name, code, desc, iconUrl, status, sortOrder } = req.body;
    
    // 验证数据
    if (!name) {
      return res.status(400).json({
        status: 'error',
        message: '渠道名称为必填项'
      });
    }
    
    if (!code) {
      return res.status(400).json({
        status: 'error',
        message: '渠道代码为必填项'
      });
    }
    
    // 验证名称重复
    const existingChannelByName = await prisma.channel.findFirst({
      where: { name }
    });
    
    if (existingChannelByName) {
      return res.status(400).json({
        status: 'error',
        message: '渠道名称已存在'
      });
    }
    
    // 验证代码重复
    const existingChannelByCode = await prisma.channel.findFirst({
      where: { code }
    });
    
    if (existingChannelByCode) {
      return res.status(400).json({
        status: 'error',
        message: '渠道代码已存在'
      });
    }
    
    // 获取当前最大排序值
    let maxSortOrder = 0;
    if (!sortOrder) {
      const lastChannel = await prisma.channel.findFirst({
        orderBy: { sortOrder: 'desc' }
      });
      
      if (lastChannel) {
        maxSortOrder = lastChannel.sortOrder + 1;
      }
    }
    
    // 创建渠道
    const channel = await prisma.channel.create({
      data: {
        name,
        code,
        desc,
        iconUrl,
        status: status !== undefined ? status : true,
        sortOrder: sortOrder || maxSortOrder
      }
    });
    
    res.status(201).json({
      status: 'success',
      message: '渠道创建成功',
      data: channel
    });
  } catch (error) {
    console.error('创建渠道失败:', error);
    res.status(500).json({
      status: 'error',
      message: '创建渠道失败',
      error: error.message
    });
  }
};

// 更新渠道
exports.updateChannel = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, desc, iconUrl, status, sortOrder } = req.body;
    
    // 验证渠道是否存在
    const existingChannel = await prisma.channel.findUnique({
      where: { id: Number(id) }
    });
    
    if (!existingChannel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    // 验证名称是否重复
    if (name && name !== existingChannel.name) {
      const duplicateChannel = await prisma.channel.findFirst({
        where: { 
          name,
          id: { not: Number(id) }
        }
      });
      
      if (duplicateChannel) {
        return res.status(400).json({
          status: 'error',
          message: '渠道名称已存在'
        });
      }
    }
    
    // 更新渠道
    const channel = await prisma.channel.update({
      where: { id: Number(id) },
      data: {
        name: name || existingChannel.name,
        desc: desc !== undefined ? desc : existingChannel.desc,
        iconUrl: iconUrl !== undefined ? iconUrl : existingChannel.iconUrl,
        status: status !== undefined ? status : existingChannel.status,
        sortOrder: sortOrder !== undefined ? sortOrder : existingChannel.sortOrder
      }
    });
    
    res.json({
      status: 'success',
      message: '渠道更新成功',
      data: channel
    });
  } catch (error) {
    console.error('更新渠道失败:', error);
    res.status(500).json({
      status: 'error',
      message: '更新渠道失败',
      error: error.message
    });
  }
};

// 删除渠道
exports.deleteChannel = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 验证渠道是否存在
    const existingChannel = await prisma.channel.findUnique({
      where: { id: Number(id) }
    });
    
    if (!existingChannel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    // 检查是否有订单使用该渠道
    const ordersCount = await prisma.order.count({
      where: { channelId: Number(id) }
    });
    
    if (ordersCount > 0) {
      return res.status(400).json({
        status: 'error',
        message: `无法删除渠道，该渠道下有${ordersCount}个订单`
      });
    }
    
    // 删除该渠道的商品价格记录
    await prisma.productPrice.deleteMany({
      where: { channelId: Number(id) }
    });
    
    // 删除渠道
    await prisma.channel.delete({
      where: { id: Number(id) }
    });
    
    res.json({
      status: 'success',
      message: '渠道删除成功'
    });
  } catch (error) {
    console.error('删除渠道失败:', error);
    res.status(500).json({
      status: 'error',
      message: '删除渠道失败',
      error: error.message
    });
  }
};

// 更新渠道排序
exports.updateChannelSort = async (req, res) => {
  try {
    const { sortData } = req.body;
    
    if (!Array.isArray(sortData)) {
      return res.status(400).json({
        status: 'error',
        message: 'sortData必须是数组'
      });
    }
    
    // 批量更新排序
    const updatePromises = sortData.map(item => 
      prisma.channel.update({
        where: { id: Number(item.id) },
        data: { sortOrder: item.sortOrder }
      })
    );
    
    await Promise.all(updatePromises);
    
    res.json({
      status: 'success',
      message: '渠道排序更新成功'
    });
  } catch (error) {
    console.error('更新渠道排序失败:', error);
    res.status(500).json({
      status: 'error',
      message: '更新渠道排序失败',
      error: error.message
    });
  }
};

// 获取渠道商品价格
exports.getChannelPrices = async (req, res) => {
  try {
    const { channelId } = req.params;
    const { page = 1, pageSize = 20, categoryId, keyword, showAllProducts } = req.query;
    
    // 验证渠道是否存在
    const channel = await prisma.channel.findUnique({
      where: { id: Number(channelId) }
    });
    
    if (!channel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    let items = [];
    let total = 0;
    
    // 根据showAllProducts参数决定是否显示所有商品
    if (showAllProducts === 'true') {
      // 查询所有商品，并关联价格
      const productWhere = {};
      
      if (categoryId) {
        productWhere.categoryId = Number(categoryId);
      }
      
      if (keyword) {
        productWhere.name = {
          contains: keyword
        };
      }
      
      // 获取总数
      total = await prisma.product.count({ 
        where: productWhere 
      });
      
      // 查询商品列表
      const products = await prisma.product.findMany({
        where: productWhere,
        include: {
          category: {
            select: {
              id: true,
              name: true
            }
          }
        },
        skip: (Number(page) - 1) * Number(pageSize),
        take: Number(pageSize),
        orderBy: {
          name: 'asc'
        }
      });
      
      // 获取这些商品在当前渠道的价格
      const productIds = products.map(p => p.id);
      const priceMap = {};
      
      if (productIds.length > 0) {
        const prices = await prisma.productPrice.findMany({
          where: {
            channelId: Number(channelId),
            productId: {
              in: productIds
            }
          }
        });
        
        // 构建价格映射
        prices.forEach(price => {
          priceMap[price.productId] = price;
        });
      }
      
      // 构建结果
      items = products.map(product => {
        const price = priceMap[product.id];
        return {
          product: {
            id: product.id,
            name: product.name,
            price: product.price,
            imageUrl: product.imageUrl,
            category: product.category
          },
          productId: product.id,
          channelId: Number(channelId),
          price: price ? price.price : product.price, // 如果没有渠道价格，使用标准价格
          discount: price ? price.discount : null
        };
      });
    } else {
      // 原来的逻辑，只显示已设置价格的商品
      // 构建查询条件
      const where = {
        channelId: Number(channelId)
      };
      
      if (categoryId) {
        where.product = {
          categoryId: Number(categoryId)
        };
      }
      
      if (keyword) {
        where.product = {
          ...where.product,
          name: {
            contains: keyword
          }
        };
      }
      
      // 查询总数
      total = await prisma.productPrice.count({ where });
      
      // 查询价格
      items = await prisma.productPrice.findMany({
        where,
        include: {
          product: {
            select: {
              id: true,
              name: true,
              price: true,
              imageUrl: true,
              category: {
                select: {
                  id: true,
                  name: true
                }
              }
            }
          }
        },
        skip: (Number(page) - 1) * Number(pageSize),
        take: Number(pageSize),
        orderBy: {
          product: {
            name: 'asc'
          }
        }
      });
    }
    
    res.json({
      status: 'success',
      data: {
        items,
        total,
        page: Number(page),
        pageSize: Number(pageSize),
        totalPages: Math.ceil(total / Number(pageSize))
      }
    });
  } catch (error) {
    console.error('获取渠道商品价格失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取渠道商品价格失败',
      error: error.message
    });
  }
};

// 设置渠道商品价格
exports.setChannelPrice = async (req, res) => {
  try {
    const { channelId } = req.params;
    const { productId, price, discount } = req.body;
    
    // 验证必填参数
    if (!productId || price === undefined) {
      return res.status(400).json({
        status: 'error',
        message: '商品ID和价格为必填项'
      });
    }
    
    // 验证渠道是否存在
    const channel = await prisma.channel.findUnique({
      where: { id: Number(channelId) }
    });
    
    if (!channel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    // 验证商品是否存在
    const product = await prisma.product.findUnique({
      where: { id: Number(productId) }
    });
    
    if (!product) {
      return res.status(404).json({
        status: 'error',
        message: '商品不存在'
      });
    }
    
    // 查找现有价格记录
    const existingPrice = await prisma.productPrice.findUnique({
      where: {
        productId_channelId: {
          productId: Number(productId),
          channelId: Number(channelId)
        }
      }
    });
    
    let result;
    
    if (existingPrice) {
      // 更新价格
      result = await prisma.productPrice.update({
        where: {
          productId_channelId: {
            productId: Number(productId),
            channelId: Number(channelId)
          }
        },
        data: {
          price: Number(price),
          discount: discount !== undefined ? Number(discount) : null
        }
      });
    } else {
      // 创建价格
      result = await prisma.productPrice.create({
        data: {
          productId: Number(productId),
          channelId: Number(channelId),
          price: Number(price),
          discount: discount !== undefined ? Number(discount) : null
        }
      });
    }
    
    res.json({
      status: 'success',
      message: '渠道商品价格设置成功',
      data: result
    });
  } catch (error) {
    console.error('设置渠道商品价格失败:', error);
    res.status(500).json({
      status: 'error',
      message: '设置渠道商品价格失败',
      error: error.message
    });
  }
};

// 批量设置渠道商品价格
exports.batchSetChannelPrices = async (req, res) => {
  try {
    const { channelId } = req.params;
    const { prices } = req.body;
    
    // 验证参数
    if (!Array.isArray(prices) || prices.length === 0) {
      return res.status(400).json({
        status: 'error',
        message: 'prices必须是非空数组'
      });
    }
    
    // 验证渠道是否存在
    const channel = await prisma.channel.findUnique({
      where: { id: Number(channelId) }
    });
    
    if (!channel) {
      return res.status(404).json({
        status: 'error',
        message: '渠道不存在'
      });
    }
    
    // 批量处理价格
    const results = await Promise.all(
      prices.map(async ({ productId, price, discount }) => {
        // 验证商品是否存在
        const product = await prisma.product.findUnique({
          where: { id: Number(productId) }
        });
        
        if (!product) {
          return {
            productId,
            success: false,
            message: '商品不存在'
          };
        }
        
        try {
          // 查找现有价格记录
          const existingPrice = await prisma.productPrice.findUnique({
            where: {
              productId_channelId: {
                productId: Number(productId),
                channelId: Number(channelId)
              }
            }
          });
          
          if (existingPrice) {
            // 更新价格
            await prisma.productPrice.update({
              where: {
                productId_channelId: {
                  productId: Number(productId),
                  channelId: Number(channelId)
                }
              },
              data: {
                price: Number(price),
                discount: discount !== undefined ? Number(discount) : null
              }
            });
          } else {
            // 创建价格
            await prisma.productPrice.create({
              data: {
                productId: Number(productId),
                channelId: Number(channelId),
                price: Number(price),
                discount: discount !== undefined ? Number(discount) : null
              }
            });
          }
          
          return {
            productId,
            success: true
          };
        } catch (error) {
          return {
            productId,
            success: false,
            message: error.message
          };
        }
      })
    );
    
    const successCount = results.filter(r => r.success).length;
    
    res.json({
      status: 'success',
      message: `已成功设置${successCount}个商品价格`,
      data: {
        results
      }
    });
  } catch (error) {
    console.error('批量设置渠道商品价格失败:', error);
    res.status(500).json({
      status: 'error',
      message: '批量设置渠道商品价格失败',
      error: error.message
    });
  }
};

// 获取渠道价格对比数据
exports.getChannelPriceComparison = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, categoryId, keyword } = req.query;
    
    // 构建查询条件
    const productWhere = {};
    
    if (categoryId) {
      productWhere.categoryId = Number(categoryId);
    }
    
    if (keyword) {
      productWhere.name = {
        contains: keyword
      };
    }
    
    // 获取所有渠道
    const channels = await prisma.channel.findMany({
      where: { status: true },
      orderBy: { sortOrder: 'asc' }
    });
    
    // 获取所有商品（分页）
    const products = await prisma.product.findMany({
      where: productWhere,
      include: {
        category: true
      },
      skip: (Number(page) - 1) * Number(pageSize),
      take: Number(pageSize),
      orderBy: { id: 'asc' }
    });
    
    // 获取商品总数
    const total = await prisma.product.count({
      where: productWhere
    });
    
    // 获取所有渠道价格
    const allPrices = await prisma.productPrice.findMany({
      where: {
        productId: {
          in: products.map(p => p.id)
        }
      }
    });
    
    // 构建价格对比数据
    const comparisonData = products.map(product => {
      // 获取该商品的所有渠道价格
      const productPrices = allPrices.filter(price => price.productId === product.id);
      
      // 构建渠道价格映射
      const channelPrices = {};
      productPrices.forEach(price => {
        channelPrices[price.channelId] = price.price;
      });
      
      return {
        productId: product.id,
        productName: product.name,
        standardPrice: product.price,
        categoryId: product.categoryId,
        categoryName: product.category?.name || '未分类',
        channelPrices
      };
    });
    
    res.json({
      status: 'success',
      data: {
        items: comparisonData,
        total,
        page: Number(page),
        pageSize: Number(pageSize),
        totalPages: Math.ceil(total / Number(pageSize))
      }
    });
  } catch (error) {
    console.error('获取渠道价格对比数据失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取渠道价格对比数据失败',
      error: error.message
    });
  }
}; 